// 下载日志打印

package internal

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"
)

type DownloadLog struct {
	totalNum           int64 // 总长度
	entryDownloadNum   int64 // 一次打印中下载的数据量
	currentDownloadNum int64 // 当前下载数据量
	mu                 *sync.RWMutex
	ctx                context.Context
	interval           time.Duration
}

func NewDownloadLog(ctx context.Context, totalNum int64, interval time.Duration) *DownloadLog {
	d := &DownloadLog{
		totalNum: totalNum,
		mu:       new(sync.RWMutex),
		ctx:      ctx,
		interval: interval,
	}

	go d.print()

	return d
}

// AddSchedule 添加下载进度（并发安全） print后重置为0
func (d *DownloadLog) AddSchedule(sch int64) {
	d.mu.Lock()
	defer d.mu.Unlock()

	d.entryDownloadNum += sch
	d.currentDownloadNum += sch
}

// 重置为0
func (d *DownloadLog) setZero() {
	d.mu.Lock()
	defer d.mu.Unlock()

	d.entryDownloadNum = 0
}

// 打印信息
func (d *DownloadLog) print() {
	ticker := time.NewTicker(d.interval)
	for {
		select {
		case <-ticker.C:
			spaceTime := d.interval
			speed := float64(d.entryDownloadNum) / d.interval.Seconds()
			schedule := float64(d.currentDownloadNum * 100 / d.totalNum)

			log.Println(fmt.Sprintf("下载进度 =====> %.2f %% %s %s/%s", schedule,
				BytesToSize(d.currentDownloadNum), BytesToSize(int64(speed)), spaceTime.String()))

			d.setZero()
		case <-d.ctx.Done():
			log.Println(fmt.Sprintf("下载进度 =====> 100.00%%"))
			return
		}
	}
}
